package foard.model
{
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import foard.core.Settings;
	
	import mx.collections.ArrayCollection;
	
	public class ThreadModel extends ArrayCollection
	{
		public var board:BoardModel;
		
		protected var array:Array;
		protected var loader:URLLoader;
		
		public function ThreadModel(data:String, board:BoardModel)
		{
			setData(data);
			
			if(_length != 0)
			{
				this.board = board;
			}
			else
			{
				trace("ThreadModel:error:data", data);
			}
		}
		
		public function setData(data:String):void
		{
			_data = data;
			
			_id = data.substring(0, data.indexOf("<>")-4);
			_title = data.substring(data.indexOf("<>")+2, data.lastIndexOf("("));
			_length = int(data.substring(data.lastIndexOf("(")+1, data.lastIndexOf(")")));
			
			array = new Array(_length);
			source = array;
		}
		
		//--
		
		private var _data:String;
		
		public function get data():String
		{
			return _data;
		}
		
		private var _id:String;
		
		public function get id():String
		{
			return _id;
		}
		
		private var _title:String;
		
		public function get title():String
		{
			return _title;
		}
		
		private var _length:int;
		
		public function get path():String
		{
			return board.path+"dat/"+id+".dat";
		}
		
		public function get datPath():String
		{
			return Settings.PROXY_PATH+path;
		}
		
		//--
		
		public function load():void
		{
			loader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, loaderCompleteHandler);
			loader.load(new URLRequest(datPath));
		}
		
		protected function loaderCompleteHandler(e:Event):void
		{
			var data:String = loader.data;
			var arr:Array = data.split("\n");
			
			for(var i:uint; i<arr.length; i++)
			{
				if(arr[i] != "")
				{
					var m:EntryModel = new EntryModel(arr[i]);
					array[i] = m;
				}
			}
			
			refresh();
		}
		
		//--
		
		public override function toString():String
		{
			return _title+"("+length+")";
		}
	}
}









